<!-- 邮件跟踪 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"/>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span><!-- 显示综合统计 -->
        </div>
      </div>
      <el-row>
        <el-button type="primary" @click="importTask">导入群发邮件任务</el-button>
        <el-button type="warning" @click="downloadFiles">下载群发邮件模板</el-button>
        <el-button type="danger" @click="clearAllRecords">清空所有记录</el-button>
        <el-button type="success" @click="exportFollow">导出关注</el-button>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
          <el-tab-pane label="日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData1" @barclick="barclick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="跟踪状态统计" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <!-- <barchart2 :title="'跟踪状态统计'" :chartData="barchartData2" @pieclick="pieclick"/> -->
                <piechart :title="'跟踪状态统计'" :chartData="barchartData2" @pieclick="pieclick"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="客户分布统计" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <transversechart :title="'客户分布统计'" :chartData="transversechartData" @pieclick="pieclick"/>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="创建时间" prop="TransTime" width="160px" align="left"></el-table-column>
          <el-table-column label="状态变更时间" prop="StatusChangeTime" width="160px" align="left"></el-table-column>
          <el-table-column label="任务名称" prop="TaskName" width="120px" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="企业名称" prop="CorpName" width="180px" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="联系人" prop="UserName" width="100px" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="目标邮箱" prop="Account" width="200px" show-overflow-tooltip align="left"></el-table-column>
          <el-table-column label="状态" align="left" width="80px">
            <template slot-scope="scope">
              <p style="color:#909399" size="small" v-if="scope.row.Status === 0">等待</p>
              <p style="color:#5fb87c" size="small" v-if="scope.row.Status === 1">送达</p>
              <p style="color:#F56C6C" size="small" v-if="scope.row.Status === 2">失败</p>
              <p style="color:#409EFF" size="small" v-if="scope.row.Status === 3">已阅</p>
              <p style="color:#df5095" size="small" v-if="scope.row.Status === 4">关注</p>
              <p style="color:#86589c" size="small" v-if="scope.row.Status === 5">发送</p>
              <p style="color:#E6A23C" size="small" v-if="scope.row.Status === 6">回复</p>
            </template>
          </el-table-column>
          <el-table-column label="软文标题" prop="Title" align="left" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column label="回复内容" prop="RspContent" align="left" width="120">
            <template slot-scope="{row}">
              <div style="display:flex;align-items:center;">
                <el-tooltip class="item" effect="dark" :content="row.RspContent" placement="top">
                  <span class="replyContent">{{ row.RspContent }}</span>
                </el-tooltip>
                <el-button style="margin-left:10px;" v-show="row.RspContent" icon="el-icon-download" circle size="mini" type="primary" @click="replyDetails(row)"></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="发件帐号" prop="FromAccount" show-overflow-tooltip  align="left"></el-table-column>
          <el-table-column label="客户地址" prop="RcvIP" show-overflow-tooltip  align="left"></el-table-column>
          <el-table-column label="客户区域" prop="Area" show-overflow-tooltip  align="left"  ></el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          background 
          :current-page=pageNum
          :page-size=pageSize
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
      <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="导入邮件任务"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="800px">
      <el-form label-width="100px" :model="resourceForm" ref="resourceForm">
        <el-form-item label='任务名称:'>
          <el-input type="texteart" v-model="TaskName" maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label='目标邮箱:'>
        <div style="display:flex; justify-content:flex-end;background:#f5f6fa;padding:10px;border: 1px solid #D3D5E0;">
          <el-button size="small" type="primary" @click="$refs.upfile.click()">点击导入</el-button>
          <input style="display:none" type="file" ref="upfile" @change="mailfileCllick($event)" accept=".xls,.xlsx">
        </div>
        <div class="key-word-textarea flex">
          <el-table stripe border :data="ToAccounts" style="width: 100%;">
            <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
            <el-table-column label="公司名称" prop="CorpName" align="left"></el-table-column>
            <el-table-column label="联系人" prop="UserName" width="120" align="left"></el-table-column>
            <el-table-column label="邮箱" prop="EMail" show-overflow-tooltip align="left"></el-table-column>
          </el-table>
        </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    </el-row>
  </div>
</template>

<script>
import base64 from 'base64-js';
import Cookies from 'js-cookie'
import XLSX from 'xlsx'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import barchart2 from "./components/barchart2.vue";
import piechart from "./components/piechart.vue";
import transversechart from "./components/transversechart.vue";
import { parseTime } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { connrequest, downloadfile } from "@/api/firstPage.js"
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart, transversechart },
  data() {
    let that = this
    return {
      tabTitle: '日统计趋势',
      activeName: "",
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      tab2: false,
      dialogVisible: false,
      fileList: [],
      barchartData1: {xAxis:[],series:[]},
      barchartData2: [],
      transversechartData: {xAxis:[],series:[]},
      tableData:[],
      searchform:{},
      searchobj: {},
      resourceForm: {},
      TaskName: '',
      ToAccounts: [],
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "统计排名", // label文字
          prop: "num", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 10, // 字段初始值,
          placeholder: "请选择统计排名", // elementui组件属性
          options: [
            { label: '前十名', value: 10 },
            { label: '前二十名', value: 20 },
            { label: '前三十名', value: 30 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.num = val
            },
          },
        },
        {
          col: 6,
          label: "邮件状态", // label文字
          prop: "Status", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 1, // 字段初始值,
          clearable: false,
          placeholder: "请选择邮件状态", // elementui组件属性
          options: [
            { label: '全部', value: 1},
            { label: '等待', value: 2},
            { label: '送达', value: 3},
            { label: '失败', value: 4},
            { label: '已阅', value: 5},
            { label: '关注', value: 6},
            { label: '回复', value: 8},
            { label: '发送', value: 7},
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Status = val
            },
          },
        },
        {
          col: 6,
          label: "目标账号", // label文字
          prop: "Account", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入目标账号", // elementui组件属性
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Account = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    let arr = [ parseTime(startTime),'']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'Status', 1)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    // 获取所有数据
    getData(){
      this.GetEMailADTraceLog()
      switch (this.tabTitle) {
        case '日统计趋势':
          this.GetEMailADTraceLogSumGroupByDate()
          break;
        case '跟踪状态统计':
          this.GetEMailADTraceLogByStatus()
          break;
        default:
          this.GetEMailADTraceLogByRcvArea()
          break;
      }
    },
    async replyDetails(row){
      const data = {
        Data: {
          FileName: row.ResFileName
        }
      }
      const res = await connrequest('GetDetailFileContent', data)
      let emailText = res.Data.Content
      this.downloadFile(emailText, "email.eml")
    },
    async clearAllRecords(){
      this.$confirm('此操作将清空所有记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await connrequest('ClearEMailADTask')
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '清空成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
      
    },
    downloadFile(content, filename, contentType) {
      var a = document.createElement("a");
      var file = new Blob([content], { type: contentType });
      a.href = URL.createObjectURL(file);
      a.download = filename;
      a.click();
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (this.tabTitle) {
        case '日统计趋势':
          this.GetEMailADTraceLogSumGroupByDate()
          break;
        case '跟踪状态统计':
          this.GetEMailADTraceLogByStatus()
          break;
        default:
          this.GetEMailADTraceLogByRcvArea()
          break;
      }
    },
    barclick(val){
      this.pageNum = 1
      this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
      this.GetEMailADTraceLog(this.searchobj)
    },
    pieclick(val,title){
      this.pageNum = 1
      if(title === '跟踪状态统计'){
        const arr = [
          { label: '等待', value: 2},
          { label: '送达', value: 3},
          { label: '失败', value: 4},
          { label: '已阅', value: 5},
          { label: '关注', value: 6},
          { label: '回复', value: 8},
          { label: '发送', value: 7},
        ]
        this.searchobj = { Status: arr.filter(item => item.label === val)[0].value }
        this.GetEMailADTraceLog(this.searchobj)
      }else{
        this.searchobj = { Descp: val }
        this.GetEMailADTraceLog(this.searchobj)
      }
    },
    // 获取邮件跟踪日志列表
    async GetEMailADTraceLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: this.searchform.TransDate || '',
          Status: this.searchform.Status || 1,
          Account: this.searchform.Account || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetEMailADTraceLog', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        item.StatusChangeTime = parseTime(item.StatusChangeTime)
        try {
          const decodedBytes = base64.toByteArray(item.Title);
          item.Title = new TextDecoder().decode(decodedBytes);
        } catch (error) {
          console.error('解码失败:', error);
          item.Title = item.Title
        }
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 获取邮件跟踪日期统计
    async GetEMailADTraceLogSumGroupByDate(){
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: this.searchform.TransDate || '',
          Status: this.searchform.Status || 1,
          Account: this.searchform.Account || '',
        }
      }
      const res = await connrequest('GetEMailADTraceLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.Name)
        series.push(item.Count)
      })
      this.barchartData1 = {xAxis,series}
    },
    // 获取邮件跟踪任务统计
    async GetEMailADTraceLogByStatus(){
      const StatusList = [
        { label: '等待', value: 2},
        { label: '送达', value: 3},
        { label: '失败', value: 4},
        { label: '已阅', value: 5},
        { label: '关注', value: 6},
        { label: '发送', value: 7},
        { label: '回复', value: 8},
      ]
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: this.searchform.TransDate || '',
          Status: this.searchform.Status || 1,
          Account: this.searchform.Account || '',
          SumCount: 10,
        }
      }
      const res = await connrequest('GetEMailADTraceLogByStatus', data)
      res.Data = res.Data || []
      res.Data.map( item => {
        arr.push({name: StatusList[item.ClassID].label, value: item.Count})
      })
      this.barchartData2 = arr
      console.log("barchartData2",this.barchartData2)
    },
    // 获取审计用户统计
    async GetEMailADTraceLogByRcvArea(){
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          TransDate: this.searchform.TransDate || '',
          Status: this.searchform.Status || 1,
          Account: this.searchform.Account || '',
          SumCount: 10,
        }
      }
      const res = await connrequest('GetEMailADTraceLogByRcvArea', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.Name)
        series.push(item.Count)
      })
      this.transversechartData = {xAxis,series}
    },
    // 导入任务
    importTask(){
      this.dialogVisible = true
    },
    // 导出关注
    async exportFollow(){
      if(sessionStorage.getItem('username') === '游客'){
        this.$message.info('很抱歉，您的角色没有导出资料。如果需要导出资料，请联系管理员获取相应权限。')
        return false
      }
      this.$alert('已经导出的数据不会重复导出', '导出关注', {
        confirmButtonText: '确定',
        type: 'warning',
        callback: async  action=> {
          if(action === 'confirm'){
            try{
              const res = await connrequest('ExportEMailADTraceLog', {}, sessionStorage.getItem('username'))
              if(res.Status.StatusCode === 0){
                let filename = this.getCurrentDate()
                const data = {
                  Data:{
                    FileName: `${filename}.xlsx`
                  }
                }
                const res = await downloadfile('Default', data)
                let blobUrl = window.URL.createObjectURL(new Blob([res]));
                const a = document.createElement('a');
                a.style.display = 'none';
                a.download = `${filename}.xlsx`;
                a.href = blobUrl;
                a.click();
              }
            }catch{
              // this.$message.error('自从上次导出后，没有需要导出的数据')
            }
          }
        }
      });
    },
    // 下载文件
    async downloadFiles(){
      if(sessionStorage.getItem('username') === '游客'){
        this.$message.info('很抱歉，您的角色没有权限下载资料。如果需要下载，请联系管理员获取相应权限。')
        return false
      }
      const a = document.createElement('a');
      a.style.display = 'none';
      a.download = '导入邮箱群发模板.xlsx';
      a.target = '_blank';
      a.href = process.env.VUE_APP_BASE_API + '/导入邮箱群发模板.xlsx';
      a.click();
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchform = val
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      let arr = [ parseTime(startTime),'']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "邮件状态"){
          item.Status = 1
        }else if(item.label === "统计排名"){
          item.initValue = 10
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'Status', 1)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEMailADTraceLog(this.searchobj)
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEMailADTraceLog(this.searchobj)
    },
    handleClick() {
      this.tab = !this.tab
    },
    async submit(){
      if(this.TaskName === ''){
        this.$message.error('任务名称不能为空')
        return false
      }
      if(this.ToAccounts.length === 0){
        this.$message.error('目标邮箱列表不能为空')
        return false
      }
      const data = {
        Data: {
          TaskName: this.TaskName,
          ToAccounts: this.ToAccounts,
        }
      }
      const res = await connrequest('ImportEMailADTask', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('邮件任务导入成功')
        this.getData()
        this.dialogVisible = false
      }
    },
    // 目标邮箱文件上传
    async mailfileCllick(e){
      // 读取表格文件
      let that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          this.da = [...ws]
          let arr = []
          this.da.map(v => {
            let obj = {}
            obj.CorpName = v['公司名称（可填空）'] + ''
            obj.UserName = v['联系人（可填空）'] + ''
            obj.EMail = v['邮箱（必填）'] + ''
            arr.push(obj)
          })
          this.ToAccounts = [...arr]
          this.ToAccounts = this.unique(this.ToAccounts)  //删除exl的重复数据
          this.tableData.forEach(item => {  //删除和tableData重复数据
            this.ToAccounts = this.ToAccounts.filter(newitem => {
              return newitem.Account !== item.Account
            })
          })
          const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          this.ToAccounts = this.ToAccounts.filter(item => {
            return email.test(item.EMail)
          })
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
.el-select {
  width: 300px;
}
.el-select ::v-deep .popper-class {
  width: 300px;
}
.iclass-text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.replyContent{
  width: 60px;
  display: inline-block;
  overflow: hidden; //超出的文本隐藏
  text-overflow: ellipsis; //溢出用省略号显示
  white-space: nowrap; //溢出不换行
}

</style>